import 'server-only' //代表仅服务端可用
import Joi from 'joi';
import resFn from '@/app/api/util/res'
import { NextRequest } from 'next/server';
import { logError } from '@/app/api/util/io/log';
import { getBody, judge, permissionJudge } from '@/app/api/util/res/handle';
import { SliceMergeReq, SliceMergeRes } from '@/types/api/file/sliceUpload';
import { stringJoi } from '@/app/api/util/Joi';
import { appendToFile, deleteFolderRecursive, getDir } from '@/app/api/util/io';
import fs from 'fs'
import { getCommonPath, getCommonPathByOwnFileName, getPublicPath, getServerPath, getTempDir, getTempFilePath } from '../../getPath';
export const dynamic = 'force-dynamic';

/**分片上传 - 合并文件 接口*/
export async function POST(request: NextRequest) {
    try {
        const user_id = "JZ8740"
        const { md5, path, suffix, ownFileName } = await judge(await getBody<SliceMergeReq>(request), { md5: stringJoi(), path: stringJoi(), suffix: stringJoi(), ownFileName: stringJoi().optional() })
        const tempDirName = getTempDir(user_id, md5)
        const commonPath = ownFileName ? getCommonPathByOwnFileName(user_id, md5, ownFileName, suffix, path) : getCommonPath(user_id, md5, suffix, path)
        const files = await getDir(tempDirName)
        files.sort((a, b) => parseInt(a.name) - parseInt(b.name));// 按照数字顺序排序文件名数组 
        const targetFilePath = getServerPath(commonPath);
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const filePath = getTempFilePath(user_id, md5, file.name)
            const content = fs.readFileSync(filePath);
            await appendToFile(content, targetFilePath)
        }
        deleteFolderRecursive(tempDirName)//删除temp的切片文件
        return resFn.success<SliceMergeRes>(getPublicPath(commonPath));
    } catch (error: any) {
        logError('分片上传 - 合并文件 接口', error)
        return resFn.errorWithReject(error);
    }
}